|
|
||||||||||||||||||||||||||||
An indispensable companion to the best-selling Core Java 2, Vol. I--Fundamentals (0-13-089468-0), Core Java 2, Volume II: Advanced Features is now available in a revised and expanded fifth edition. It delivers the same real-world guidance you need to solve even the most challenging programming problems and offers an all-new chapter on XML and Java, plus thoroughly revamped coverage of many advanced features—from collections to native methods, security to Swing.
Cay Horstmann identifies the problems experienced Java platform developers encounter most often, and delivers insightful, expert-level guidance for addressing them-together with even more of the robust, sample code that have made Core Java an international bestseller for five straight years. You'll gain new insights into networking, remote objects, JDBC API, internationalization, and a whole lot more.
For experienced programmers, Core Java 2, Volume 2: Advanced Features provides the answers that they need to take full advantage of the power of Java technology and to get the job done as efficiently as possible.
State-of-the-art information for advanced Java technology development, including:
Thoroughly updated coverage of multithreading, collections, and networking
Completely revised coverage of remote objects
Detailed new chapter on XML and Java
Sophisticated new techniques for utilizing JavaBeans(tm) component architecture
Advanced GUI-building techniques leveraging both Swing and AWT
777
© 2002 Sun Microsystems, Inc.—
Printed in the United States of America.
901 San Antonio Road, Palo Alto, California
94303 U.S.A.
All rights reserved. This product and related documentation are protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or related documentation may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.
RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is subject to the restrictions set forth in DFARS 252.227-7013 (c)(1)(ii) and FAR 52.227-19.
The products described may be protected by one or more U.S. patents, foreign patents, or pending applications.
TRADEMARKS—Sun, Sun Microsystems, the Sun logo, Java, and all Java-based trademarks are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.
The publisher offers discounts on this book when ordered in bulk quantities. For more information, contact: Corporate Sales Department, Phone: 800-382-3419; Fax: 201-236-7141; E-mail: corpsales@prenhall.com; or write: Prentice Hall PTR, Corp. Sales Dept., One Lake Street, Upper Saddle River, NJ 07458.
Editorial/production supervision: Navta Associates
Acquisitions editor: Gregory G. Doench
Editorial assistant: Brandt Kenna
Manufacturing manager: Alexis R. Heydt-Long
Cover design director: Jerry Votta
Cover designer: Talar Agasyan-Boorujy
Cover illustration: Karen Strelecki
Marketing manager: Debby van Dijk
Project coordinator: Anne Garcia
Interior designer: Gail Cocker-Bogusz
Sun Microsystems Press:
Marketing manager: Michael Llwyd Alread
Publisher: Rachel Borden
10 9 8 7 6 5 4 3 2
Sun Microsystems Press
A Prentice Hall Title
Tables
2-1 Hash codes resulting from the hashCode function
2-2 Hash codes of objects with identical contents
2-3 Adding elements into hash and tree sets
3-1 Convenience methods for response header values
4-6 SQL data types and their corresponding Java language types
4-9 ResultSet concurrency values
4-10 Five columns of the result set
5-1 Naming conventions for RMI classes
7-1 The Porter-Duff Composition Rules
7-3 Document Flavors for Print Services
7-5 Capabilities of the Java data transfer mechanism
7-6 Data Transfer Support in Swing Components
9-1 Call stack during permission checking
9-2 Permissions and their associated targets and actions
10-1 Common ISO-639 language codes
10-2 Common ISO-3166 country codes
10-3 Collations with different strengths
10-4 String selected by ChoiceFormat
11-2 Correspondence between Java array types and C types
12-1 Rules for Element Content
Code Examples
1-12 ProgressMonitorInputStreamTest.java
7-15 StreamPrintServiceTest.java
8-14 DoubleArrayEditorPanel.java
9-7 WordCheckSecurityManager.java
10-10 RetireStrings_de.properties
10-11 RetireStrings_zh.properties
Figures
1-1 Using a thread to animate a bouncing ball
1-2 The Event Dispatch and Ball Threads
1-4 Time-slicing on a single CPU
1-6 Threads with different priorities
1-7 Simultaneous access by two threads
1-8 Comparison of unsynchronized and synchronized threads
1-10 Exception reports in the console
1-11 Threads in a Swing program
1-12 This file has 36 images of a globe
1-13 Picking a frame from a strip of frames
1-16 A progress monitor dialog
1-17 A progress monitor for an input stream
2-4 Removing an element from an array
2-6 Removing an element from a linked list
2-7 Adding an element to a linked list
2-10 The interfaces of the collections framework
2-11 Classes in the collections framework
2-12 Legacy classes in the collections framework
2-13 The customized Hello World program
3-1 Output of the "time of day" service
3-2 A client connecting to a server port
3-3 Using telnet to access an HTTP port
3-5 Simultaneous access to the threaded echo server
3-9 Data flow during execution of a CGI script
3-10 A web form to request census data
3-12 Applet security disallows connection to a third party
3-13 A firewall provides security
3-14 Data flow in the weather report applet
4-1 JDBC-to-database communication path
4-2 A client/server application
4-4 Sample table containing the HTML books
4-5 Two tables joined together
4-7 A GUI view of a query result
5-1 Transmitting objects between client and server
5-2 Invoking a remote method on a server object
5-5 Calling the remote getDescription method
5-6 Obtaining product suggestions from the server
5-7 Copying local parameter and result objects
5-8 Only the ProductImpl methods are remote
5-9 BookImpl has additional remote methods
5-10 Inheritance of equals and hashCode methods
6-2 Choosing from a very long list of selections
6-3 A list box with rendered cells
6-5 A hierarchy of countries, states, and cities
6-10 Collapsed and expanded subtrees
6-11 A tree with the Windows look and feel
6-12 A tree with no connecting lines
6-13 A tree with the horizontal line style
6-14 A tree with a root handle
6-19 The scroll pane scrolls to display a new node
6-24 An object inspection tree
6-29 Displaying a query result in a table
6-30 Sorting the rows of a table
6-32 A table with cell renderers
6-34 Relationship between Table classes
6-35 Editing the cell color with a color chooser
6-37 Selecting a range of cells
6-38 The editor pane displaying an HTML page
6-39 The editor pane in edit mode
6-40 A frame with two nested split panes
6-42 A tabbed pane with scrolling tabs
6-43 A multiple document interface application
6-44 A Java application with three internal frames
6-47 The user can veto the close property
7-2 The bounding rectangle of an ellipse and an arc
7-3 Relationships between the shape classes
7-4 Constructing a RoundRectangle2D
7-5 Constructing an elliptical arc
7-10 Constructive Area Geometry Operations
7-18 User and device coordinates
7-19 The fundamental transformations
7-20 Composing transformations
7-21 The TransformTest program
7-23 Overlaying a partially transparent rectangle on an image
7-24 Designing a Composition Rule
7-25 Porter-Duff Composition Rules
7-26 The CompositeTest program
7-28 The RenderingHints program
7-34 A Cross-Platform Print Dialog
7-36 A Cross-Platform Page Setup Dialog
7-38 A Windows page setup dialog
7-40 Printing a page of a banner
7-42 Viewing a PostScript File
7-44 The Attribute Set Hierarchy
7-45 The TextTransferTest program
7-46 The Windows clipboard viewer after a copy
7-47 Copying from a Java program to a native program
7-48 Copying from a native program to a Java program
7-49 Transferring Local Objects
7-50 Data is copied between two instances of a Java application
7-51 Initiating a drag operation
7-52 Cursor shapes over drop targets
7-53 The DropTargetTest program
7-54 The DragSourceTest program
7-55 The Swing Drag and Drop Test Program
8-1 The Properties window in Visual Basic for an image application
8-3 Adding a Bean to a Palette in Forte
8-9 Using a property editor to set properties
8-10 The ImageViewerBean at work
8-11 The Events Tab of the Property Inspector
8-12 Event Handling Code in The Edit Window
8-16 Listening to a Custom Event
8-18 The property inspector for the chart bean
8-19 The TitlePositionEditor at work
8-21 The custom editor dialog for editing an array
8-22 The customizer for the ChartBean
8-24 The customizer of the SpinBean
8-25 The SpinBean coupled with an IntTextBean buddy
8-27 Relationships between the bean context classe
8-28 The Message Tracer window
9-1 The ClassLoaderTest program
9-2 Modifying bytecodes with a hex editor
9-3 Loading a corrupted class file raises a method verification error
9-5 Permission hierarchy in JDK 1.2
9-6 Relationship between security classes
9-7 The policy tool displaying code sources
9-8 The policy tool displaying the permissions for a code source
9-9 Editing a permission with the policy tool
9-10 The PermissionTest program
9-11 The SecurityManagerTest program
9-12 Computing a message digest
9-13 Public key signature exchange using DSA
9-14 Authentication through a trusted intermediary
9-15 Authentication through a trusted intermediary's signature
9-17 ASN.1 definition of X.509v3
9-18 The FileReadApplet program
9-19 Launching a signed applet
10-1 The NumberFormatTest program
10-2 The DateFormatTest program running under Chinese Windows
10-3 The CollationTest program
10-4 The TextBoundaryTest program
10-5 The retirement calculator in English
10-6 The retirement calculator in German
10-7 The retirement calculator in Chinese
11-2 Inheritance hierarchy of array types
12-1 The Node interfaces and its subinterfaces
12-3 A parse tree of an XML document
12-4 A font dialog defined by an XML layout
12-6 The Apache Batik SVG Viewer
12-7 Applying XSL Transformations
The book you have in your hands is the second volume of the fourth edition of Core Java. The first edition appeared in early 1996, the second in late 1996, and the third in 1997/1998. The first two editions appeared in a single volume, but the second edition was already 150 pages longer than the first, which was itself not a thin book. When we sat down to work on the third edition, it became clear that a one-volume treatment of all the features of the Java™ platform that a serious programmer needs to know was no longer possible. Hence, we decided to break up the third edition into two volumes. In the fourth edition, we again organized the material into two volumes. However, we rearranged the materials, moving streams into Volume 1 and collections into Volume 2.
The first volume covers the essential features of the language; this volume covers the advanced topics that a programmer will need to know for professional software development. Thus, as with the first volume and the previous editions of this book, we still are targeting programmers who want to put Java technology to work on real projects.
Please note: If you are an experienced developer who is comfortable with the new event model and advanced language features such as inner classes, you need not have read the first volume in order to benefit from this volume. (While we do refer to sections of the previous volume when appropriate and, of course, hope you will buy or have bought Volume 1, you can find the needed background material in any comprehensive introductory book about the Java platform.)
Finally, when any book is being written, errors and inaccuracies are inevitable. We would very much like to hear about them. Of course, we would prefer to hear about them only once. For this reason, we have put up a web site at http://www.horstmann.com/corejava.html with an FAQ, bug fixes, and workarounds. Strategically placed at the end of the bug report web page (to encourage you to read the previous reports) is a form that you can use to report bugs or problems and to send suggestions for improvements to future editions.
The chapters in this book are, for the most part, independent of each other. You should be able to delve into whatever topic interests you the most and read the chapters in any order.
Chapter 1 covers multithreading, which enables you to program tasks to be done in parallel. (A thread is a flow of control within a program.) We show you how to set up threads and how to make sure none of them get stuck. We put this knowledge to practical use by example, showing you the techniques needed to build timers and animations.
The topic of Chapter 2 is the collections framework of the Java 2 platform. Whenever you want to collect multiple objects and retrieve them later, you will want to use a collection that is best suited for your circumstances, instead of just tossing the elements into a Vector. This chapter shows you how to take advantage of the standard collections that are prebuilt for your use.
Chapter 3 covers one of the most exciting APIs in the Java platform: the networking API. Java makes it phenomenally easy to do complex network programming. Not only do we cover this API in depth, we also discuss the important consequences of the applet security model for network programming.
Chapter 4 covers JDBC™, the Java database connectivity API. We show you how to write useful programs to handle realistic database chores, using a core subset of the JDBC API. Please note that this is not a complete treatment of everything you can do with the rich JDBC API. (A complete treatment of the JDBC API would require a book almost as long as this one.)
Chapter 5 covers remote objects and Remote Method Invocation (RMI). This API lets you work with Java objects that are distributed over multiple machines. We also show you where the rallying cry of "objects everywhere" can realistically be used.
Chapter 6 contains all the Swing material that didn't make it into Volume 1, especially the important but complex tree and table components. We show the basic uses of editor panes and the Java technology implementation of a "multiple document" interface. Again, we focus on the most useful constructs that you are likely to encounter in practical programming, since an encyclopedic coverage of the entire Swing library would fill several volumes and would only be of interest to dedicated taxonomists.
Chapter 7 covers the Java 2D API that you can use to create realistic drawings. The chapter also covers some advanced features of the Abstract Windowing Toolkit (AWT) that seemed too specialized for coverage in Volume 1 but are, nonetheless, techniques that should be part of every programmer's toolkit. These features include printing and the APIs for cut-and-paste and drag-and-drop. We actually take the cut-and-paste API one step further than Sun Microsystems itself did: We show you how to cut and paste serializable Java objects between different programs in the Java programming language via the system clipboard.
Chapter 8 shows you what you need to know about the component API for the Java platform—JavaBeans™. You will see how to write your own beans that other programmers can manipulate in integrated builder environments. (We do not cover the various builder environments that are designed to manipulate beans, however.) The JavaBeans™ component technology is an extraordinarily important technology for the eventual success of Java technology because it can potentially bring the same ease of use to user interface programming environments that ActiveX controls give to the millions of Visual Basic programmers. Of course, since these components are written in the Java programming language, they have the advantage over ActiveX controls in that they are immediately usable across other platforms and capable of fitting into the sophisticated security model of the Java platform.
In fact, Chapter 9 takes up that security model. The Java platform was designed from the ground up to be secure, and this chapter takes you under the hood to see how this design is implemented. We show you how to write your own class loaders and security managers for special-purpose applications. Then, we take up the new security API that allows for such important features as signed classes.
Chapter 10 discusses a specialized feature that we believe can only grow in importance: internationalization. The Java programming language is one of the few languages designed from the start to handle Unicode, but the internationalization support in the Java platform goes much further. As a result, you can internationalize Java applications so that they not only cross platforms but cross country boundaries as well. For example, we show you how to write a retirement calculator applet that uses either English, German, or Chinese—depending on the locale of the browser.
Chapter 11 takes up native methods, which let you call methods written for a specific machine such as the Microsoft Windows API. Obviously, this feature is controversial: Use native methods, and the cross-platform nature of the Java platform vanishes. Nonetheless, every serious programmer writing Java applications for specific platforms needs to know these techniques. There will be times when you need to turn to the operating system's API for your target platform when you are writing a serious application. We illustrate this by showing you how to access the registry functions in Windows.
As is common in many computer books, we use courier type to represent computer code.
NOTE
![]() |
Notes are tagged with a "notepad" icon that looks like this. |
TIP
![]() |
Helpful tips are tagged with this icon. |
CAUTION
![]() |
Notes that warn of pitfalls or dangerous situations are tagged with a "Caution" icon. |
C++ NOTE
|
|
There are a number of C++ notes that explain the difference between the Java programming language and C++.You can skip them if you aren't interested in C++. |
![]()
The Java platform comes with a large programming library or Application
Programming Interface (API). When using an API call for the first time, we add a
short summary description, tagged with an API icon. These descriptions are a bit
more informal but also a little more informative than those in the official
on-line API documentation.
Programs whose source code is on the CD-ROM are listed as examples, for instance, Example 5-8: WarehouseServer.java refers to the corresponding code on the CD-ROM. You can also download these example files from the Web.
A Java object is an object that is created by a program that was written in the Java programming language.
A Java application is a program that was written in the Java programming language and that is launched by a Java virtual machine (that is, a virtual machine for the Java platform).
Writing a book is always a monumental effort, and rewriting doesn't seem to be much easier, especially with such a rapid rate of change in Java technology. Making a book a reality takes many dedicated people, and it is my great pleasure to acknowledge the contributions of the entire Core Java team.
Our long-suffering editor Greg Doench of Prentice Hall PTR once again did a great job, coordinating all aspects of this complex project. Julie Bettis copyedited the manuscript, with an excellent eye for consistency and always on the lookout for Teutonic constructions and violations of the Java trademark rules.
Kathi Beste, Bert Stutz, and Marilyn Stutz at Navta Associates, Inc., once again delivered an attractively typeset book. A number of other individuals at Prentice Hall PTR and Sun Microsystems Press also provided valuable assistance, but they managed to stay behind the scenes. I'd like them all to know how much I appreciate their efforts. My thanks also to my co-author of earlier editions, Gary Cornell, who has since moved on to other ventures.
I am very grateful to the excellent reviewing team who found many embarrassing errors and made lots of thoughtful suggestions for improvement. The new material for this edition was reviewed by David Geary, Bob Lynch, Paul Philion, and George Thiruvathukal.
Reviewers of earlier editions are Alec Beaton (PointBase, Inc.), Joshua Bloch (Sun Microsystems), David Brown, Dr. Nicholas J. De Lillo (Manhattan College), Rakesh Dhoopar (Oracle), Angela Gordon (Sun Microsystems), Dan Gordon (Sun Microsystems), Rob Gordon, Cameron Gregory (olabs.com), Marty Hall (The Johns Hopkins University Applied Physics Lab), Vincent Hardy (Sun Microsystems), Vladimir Ivanovic (PointBase, Inc.), Jerry Jackson (ChannelPoint Software), Tim Kimmet (Preview Systems), Chris Laffra, Charlie Lai (Sun Microsystems),
Doug Langston, Doug Lea (SUNY Oswego), Gregory Longshore, Mark Morrissey (The Oregon Graduate Institute), Mahesh Neelakanta (Florida Atlantic University), Blake Ragsdell, Stuart Reges (University of Arizona), Peter Sanders (ESSI University, Nice, France), Devang Shah (Sun Microsystems), Christopher Taylor, Luke Taylor (Valtech), Kim Topley, Janet Traub, Peter van der Linden (Sun Microsystems), and Burt Walsh.
Most importantly, my love, gratitude, and apologies go to my wife Hui-Chen and my children Tommy and Nina for their continuing support of this never-ending project.
Cay Horstmann
Cupertino, November 2001